//
//  rootViewController.m
//  QRCode
//
//  Created by liguowei on 15/11/18.
//  Copyright © 2015年 liguiwei. All rights reserved.
//

#import "UWRQViewController.h"
#import <AVFoundation/AVFoundation.h>

static const char *UWlgwQRCodeQueueName = "UWlgwQRCodeQueue";

@interface UWRQViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic) AVCaptureSession *captureSession;
@property (nonatomic) AVCaptureVideoPreviewLayer *videPreviewLayer;
@property (nonatomic) BOOL lastResult;

@property (nonatomic, strong) UIView *photo;
@property (nonatomic, assign) BOOL isOpenLight;
@property (nonatomic, strong) UILabel *alertLabel;
@property (nonatomic, strong) UIButton *switchBtn;
@property (nonatomic, strong) UILabel *warmLabel;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger canAdd;
@property (nonatomic, strong) UIButton *finishButton;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation UWRQViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    self.tabBarController.tabBar.translucent = YES;
    self.navigationItem.title = @"扫描二维码";
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backToHome) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.view.backgroundColor = [UIColor whiteColor];
    [self layoutView];
    _lastResult = YES;
    [self startReading];
    self.dataArray = [NSMutableArray array];
    self.canAdd = 0;
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    _finishButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, space(100), space(90))];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_finishButton];
    [_finishButton setTitle:@"完成" forState:UIControlStateNormal];
    [_finishButton setTitleColor:ZCColor(0xff8213, 1) forState:UIControlStateNormal];
    [_finishButton addTarget:self action:@selector(finishedScan:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_finishButton];
    if (self.sweepStill) {
        _finishButton.hidden = NO;
    }else {
        _finishButton.hidden = YES;
    }
}

- (void)backToHome {
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)finishedScan:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(uwRQFinishedStillScan:)]) {
        [self.delegate uwRQFinishedStillScan:self.dataArray];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidDisappear:(BOOL)animated{
    [self stopReading];
}

- (void)layoutView {
    _photo = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_photo];
    
   

    _QRview = [[RQView alloc] initWithFrame:CGRectMake(0, 0, 230,
                                                       230)];
    [self.view addSubview:_QRview];
    CGFloat centerY = self.view.center.y;//- 64 / 2 - 10;
//    _photo.center =
    _QRview.center = CGPointMake(self.view.center.x, centerY);

    _alertLabel = [[UILabel alloc]
        initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 60)];
    _alertLabel.font = [UIFont systemFontOfSize:15];
    _alertLabel.backgroundColor = [UIColor whiteColor];
    _alertLabel.textAlignment = NSTextAlignmentCenter;
    _alertLabel.text = _alertTitle;
    _alertLabel.textColor = [UIColor blackColor];
    _alertLabel.alpha = 0.6;
    [self.view addSubview:_alertLabel];

    _warmLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 20)];
    _warmLabel.font = [UIFont systemFontOfSize:14];
    _warmLabel.textColor = ZCColor(0xffffff, 1);
    _warmLabel.textAlignment = NSTextAlignmentCenter;
    _warmLabel.text = @"将二维码图标对准扫描框即可自动扫描";
    CGPoint centerT = _warmLabel.center;
    centerT.x = self.view.center.x;
    centerT.y = _QRview.center.y + _QRview.bounds.size.height / 2 + 25;
    _warmLabel.center = centerT;
    [self.view addSubview:_warmLabel];

    _switchBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    CGPoint centerS = _warmLabel.center;
    centerS.x = self.view.center.x;
    centerS.y = _QRview.center.y + _QRview.bounds.size.height / 2 + 100;
    _switchBtn.center = centerS;
    [_switchBtn setImage:[UIImage imageNamed:@"switchOn"] forState:UIControlStateSelected];
    [_switchBtn setImage:[UIImage imageNamed:@"switchOff"] forState:UIControlStateNormal];
    _switchBtn.selected = NO;
    [_switchBtn addTarget:self
                   action:@selector(lightControl:)
         forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_switchBtn];
}

- (BOOL)startReading {
    MMPopupItemHandler alertBlock = ^(NSInteger index) {
        switch (index) {
            case 0: {
                NSURL *url2 = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url2];
            } break;

            default:
                break;
        }
        NSLog(@"clickd %@ button", @(index));
    };
    NSArray *items = @[
        MMItemMake(@"好的", MMItemTypeHighlight, alertBlock),
        MMItemMake(@"算了", MMItemTypeNormal, alertBlock)
    ];
    MMAlertView *alertView = [[MMAlertView alloc]
        initWithTitle:@"友情提醒"
               detail:@"您还没有打开相机权限，是否前往获取？"
                items:items];
    alertView.attachedView.mm_dimBackgroundBlurEnabled = NO;
    alertView.attachedView.mm_dimBackgroundBlurEffectStyle = UIBlurEffectStyleExtraLight;
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authStatus == AVAuthorizationStatusRestricted ||
        authStatus == AVAuthorizationStatusDenied) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            [alertView show];

        } else {
            [alertView show];
        }
        return NO;
    }

    NSError *error;

    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    AVCaptureDeviceInput *input =
        [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];

    _captureSession = [[AVCaptureSession alloc] init];
    _captureSession.sessionPreset = AVCaptureSessionPreset1280x720;

    [_captureSession addInput:input];

    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];

    CGSize size = self.view.bounds.size;
    CGRect cropRect = _QRview.frame;
    captureMetadataOutput.rectOfInterest =
        CGRectMake(cropRect.origin.y / size.height, cropRect.origin.x / size.width,
                   cropRect.size.height / size.height, cropRect.size.width / size.width);

    [_captureSession addOutput:captureMetadataOutput];

    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create(UWlgwQRCodeQueueName, NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];

    [captureMetadataOutput
        setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode,
                                                         AVMetadataObjectTypeEAN13Code,
                                                         AVMetadataObjectTypeEAN8Code,
                                                         AVMetadataObjectTypeCode128Code, nil]];

    _videPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [_videPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videPreviewLayer setFrame:_photo.layer.bounds];
    [_photo.layer addSublayer:_videPreviewLayer];

    [_captureSession startRunning];

    return YES;
}

- (void)stopReading {
    // 停止会话
    [_captureSession stopRunning];
    _captureSession = nil;
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput
    didOutputMetadataObjects:(NSArray *)metadataObjects
              fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        NSString *result;
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            result = metadataObj.stringValue;
            NSLog(@"扫描结果:%@", result);
        } else {
            NSLog(@"不是二维码");
            result = metadataObj.stringValue;
        }

        if (_lastResult) {
            [self performSelectorOnMainThread:@selector(reportScanResult:)
                                   withObject:result
                                waitUntilDone:NO];
        }
    }
}

#pragma mark uwRQDelegate

- (void)reportScanResult:(NSString *)result {
    if (self.sweepStill) {
        if (!_lastResult) {
            return;
        }
        _lastResult = NO;
        
        if ([self.vinArr containsObject:result] || [self.qrArr containsObject:result]) {
            for (int i = 0; i < self.dataArray.count; i++) {
                if ([self.vinArr[i] isEqualToString:result] || [self.qrArr[i] isEqualToString:result]) {
                    self.canAdd++;
                    [self.hud showAnimated:YES];
                    self.hud.mode = MBProgressHUDModeText;
                    self.hud.label.text = @"已扫描";
                    [self.hud hideAnimated:YES afterDelay:HudTime];
                }
            }
        }else {
            [self.hud showAnimated:YES];
            self.hud.mode = MBProgressHUDModeText;
            self.hud.label.text = @"车架号不匹配";
            [self.hud hideAnimated:YES afterDelay:HudTime];
            self.canAdd++;
        }
            
        if (self.canAdd == 0) {
            [self.dataArray addObject:result];
            self.hud.mode = MBProgressHUDModeText;
            self.hud.label.text = @"扫描成功";
            [self.hud showAnimated:YES];
            [self.hud hideAnimated:YES afterDelay:HudTime];
        }
        [self stopReading];
        sleep(1.5);
        [self startReading];
        _lastResult = YES;
        self.canAdd = 0;
        
    }else {
        [self stopReading];
        if (!_lastResult) {
            return;
        }
        _lastResult = NO;
        
        // 以下处理了结果，继续下次扫描
        [_QRview removeFromSuperview];
        _QRview = nil;
        
        _lastResult = YES;
        if (self.navigationController) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
        if ([self.delegate respondsToSelector:@selector(uwRQFinshedScan:)]) {
            [self.delegate uwRQFinshedScan:result];
        }
    }
    
}


- (void)lightControl:(UIButton *)sender {
    sender.selected = !sender.selected;
    [self switchLightWithOrder:_isOpenLight];
}

- (void)switchLightWithOrder:(bool)isOpenLight {
    isOpenLight = !isOpenLight;
    _isOpenLight = isOpenLight;
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]) {
            [device lockForConfiguration:nil];
            if (isOpenLight) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
            }
            [device unlockForConfiguration];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
